package com.example.show_auto.ui.pages

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.show_auto.data.SettingsStorage
import androidx.compose.ui.platform.LocalContext
import com.example.show_auto.data.UpdateManager
import com.example.show_auto.data.UpdateInfo
import kotlinx.coroutines.launch
import android.content.Intent
import android.net.Uri
import kotlin.system.exitProcess

/**
 * 系统配置页面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SystemConfigPage(
    onMenuClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    val context = LocalContext.current
    val settingsStorage = remember { SettingsStorage(context) }
    val updateManager = remember { UpdateManager(context) }
    val scope = rememberCoroutineScope()
    
    // 主题设置状态
    var themeMode by remember { mutableStateOf(settingsStorage.getThemeMode()) }
    
    // 更新相关状态
    var isCheckingUpdate by remember { mutableStateOf(false) }
    var updateInfo by remember { mutableStateOf<UpdateInfo?>(null) }
    var showUpdateDialog by remember { mutableStateOf(false) }
    var showChangelogDialog by remember { mutableStateOf(false) }
    val currentVersion = remember { updateManager.getCurrentVersion() }
    


    Column(
        modifier = modifier.fillMaxSize()
    ) {
        // 顶部应用栏
        TopAppBar(
            title = {
                Text(
                    text = "系统设置",
                    fontWeight = FontWeight.Medium
                )
            },
            navigationIcon = {
                IconButton(onClick = onMenuClick) {
                    Icon(
                        imageVector = Icons.Default.Menu,
                        contentDescription = "菜单"
                    )
                }
            },
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
                navigationIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer
            )
        )

        // 主要内容
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp)
                .verticalScroll(rememberScrollState()),
            verticalArrangement = Arrangement.spacedBy(24.dp)
        ) {
            // 主题设置卡片
            Card(
                modifier = Modifier.fillMaxWidth(),
                elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp),
                    verticalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    // 标题
                    Text(
                        text = "主题设置",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.primary
                    )

                    // 外观模式设置
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Column {
                            Text(
                                text = "外观模式",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Medium
                            )
                            Text(
                                text = "跟随系统",
                                fontSize = 14.sp,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }

                        // 主题切换按钮
                        Row(
                            horizontalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            // 浅色主题按钮
                            OutlinedButton(
                                onClick = {
                                    themeMode = 1
                                    settingsStorage.saveThemeMode(1)
                                },
                                colors = ButtonDefaults.outlinedButtonColors(
                                    containerColor = if (themeMode == 1) MaterialTheme.colorScheme.primary else Color.Transparent,
                                    contentColor = if (themeMode == 1) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.primary
                                ),
                                modifier = Modifier.height(40.dp)
                            ) {
                                Text(
                                    text = "浅色",
                                    fontSize = 14.sp
                                )
                            }

                            // 深色主题按钮
                            OutlinedButton(
                                onClick = {
                                    themeMode = 2
                                    settingsStorage.saveThemeMode(2)
                                },
                                colors = ButtonDefaults.outlinedButtonColors(
                                    containerColor = if (themeMode == 2) MaterialTheme.colorScheme.primary else Color.Transparent,
                                    contentColor = if (themeMode == 2) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.primary
                                ),
                                modifier = Modifier.height(40.dp)
                            ) {
                                Text(
                                    text = "深色",
                                    fontSize = 14.sp
                                )
                            }
                        }
                    }
                }
            }

            // 其他设置卡片 - 版本更新
            Card(
                modifier = Modifier.fillMaxWidth(),
                elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp),
                    verticalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    Text(
                        text = "版本更新",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.primary
                    )

                    // 版本信息
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Column {
                            Text(
                                text = "当前版本",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Medium
                            )
                    Text(
                                text = "v$currentVersion",
                        fontSize = 14.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }

                        Row(
                            horizontalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            OutlinedButton(
                                onClick = {
                                    scope.launch {
                                        isCheckingUpdate = true
                                        try {
                                            val info = updateManager.checkForUpdate()
                                            updateInfo = info
                                            if (info.hasUpdate) {
                                                // 如果是强制更新，设置强制更新状态
                                                if (info.forceUpdate) {
                                                    settingsStorage.setForceUpdatePending(true)
                                                }
                                                showUpdateDialog = true
                                            }
                                        } finally {
                                            isCheckingUpdate = false
                                        }
                                    }
                                },
                                enabled = !isCheckingUpdate,
                                modifier = Modifier.height(40.dp)
                            ) {
                                if (isCheckingUpdate) {
                                    CircularProgressIndicator(
                                        modifier = Modifier.size(16.dp),
                                        strokeWidth = 2.dp
                                    )
                                    Spacer(modifier = Modifier.width(8.dp))
                                }
                                Text(
                                    text = if (isCheckingUpdate) "检查中..." else "检查更新",
                                    fontSize = 14.sp
                                )
                            }
                            
                            OutlinedButton(
                                onClick = { showChangelogDialog = true },
                                modifier = Modifier.height(40.dp)
                            ) {
                                Text(
                                    text = "更新日志",
                                    fontSize = 14.sp
                                )
                            }
                        }
                    }

                    // 显示最后检查结果
                    updateInfo?.let { info ->
                        if (!info.hasUpdate && !isCheckingUpdate) {
                            Row(
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    imageVector = Icons.Default.CheckCircle,
                                    contentDescription = null,
                                    tint = MaterialTheme.colorScheme.primary,
                                    modifier = Modifier.size(16.dp)
                                )
                                Spacer(modifier = Modifier.width(8.dp))
                                Text(
                                    text = if (info.updateMessage.contains("网络") || info.updateMessage.contains("失败")) {
                                        info.updateMessage
                                    } else {
                                        "已是最新版本"
                                    },
                                    fontSize = 14.sp,
                                    color = if (info.updateMessage.contains("网络") || info.updateMessage.contains("失败")) {
                                        MaterialTheme.colorScheme.error
                                    } else {
                                        MaterialTheme.colorScheme.primary
                                    }
                                )
                            }
                        }
                    }

                    HorizontalDivider()

                    // 自动更新说明
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            imageVector = Icons.Default.Info,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.size(20.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = "应用每天首次启动时自动检查更新",
                            fontSize = 14.sp,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                    }
                }
            }
        }
    }

    // 更新对话框
    if (showUpdateDialog && updateInfo != null) {
        val info = updateInfo!!
        AlertDialog(
            onDismissRequest = { 
                if (!info.forceUpdate) {
                    showUpdateDialog = false 
                } else {
                    // 强制更新时，拒绝更新则退出应用
                    exitProcess(0)
                }
            },
            title = {
                Text(
                    text = if (info.forceUpdate) "强制更新" else "发现新版本",
                    color = if (info.forceUpdate) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary
                )
            },
            text = {
                Column(
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    Text("最新版本：v${info.latestVersion}")
                    Text("当前版本：v${info.currentVersion}")
                    
                    if (info.updateMessage.isNotEmpty()) {
                        HorizontalDivider()
                        Text(
                            text = "更新内容：",
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colorScheme.primary
                        )
                        SelectionContainer {
                            Text(
                                text = info.updateMessage,
                                style = MaterialTheme.typography.bodyMedium
                            )
                        }
                    }
                    
                    if (info.forceUpdate) {
                        HorizontalDivider()
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            Icon(
                                Icons.Default.Warning,
                                contentDescription = null,
                                tint = MaterialTheme.colorScheme.error
                            )
                            Text(
                                text = "此版本为强制更新，必须更新后才能继续使用应用\n点击任何位置拒绝更新将自动退出应用",
                                color = MaterialTheme.colorScheme.error,
                                fontWeight = FontWeight.Bold
                            )
                        }
                    }
                }
            },
            confirmButton = {
                Button(
                    onClick = {
                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(info.downloadUrl))
                        context.startActivity(intent)
                        if (!info.forceUpdate) {
                            showUpdateDialog = false
                        } else {
                            // 强制更新时，跳转到下载页面后退出应用
                            // 保持强制更新状态，确保用户必须完成更新才能重新进入应用
                            exitProcess(0)
                        }
                    }
                ) {
                    Text("立即更新")
                }
            },
            dismissButton = if (!info.forceUpdate) {
                {
                    TextButton(
                        onClick = { showUpdateDialog = false }
                    ) {
                        Text("稍后更新")
                    }
                }
            } else null
        )
    }
    
    // 更新日志对话框
    if (showChangelogDialog) {
        ChangelogDialog(
            onDismiss = { showChangelogDialog = false }
        )
    }
}

@Composable
private fun ChangelogDialog(
    onDismiss: () -> Unit
) {
    // 展开状态管理 - 最新版本默认展开，其他收起
    var version107Expanded by remember { mutableStateOf(true) }  // 最新版本默认展开
    var version106Expanded by remember { mutableStateOf(false) } // 其他版本默认收起
    var version105Expanded by remember { mutableStateOf(false) } // 其他版本默认收起
    var version104Expanded by remember { mutableStateOf(false) } // 其他版本默认收起
    var version103Expanded by remember { mutableStateOf(false) } // 其他版本默认收起
    var version102Expanded by remember { mutableStateOf(false) } // 其他版本默认收起
    var version101Expanded by remember { mutableStateOf(false) } // 其他版本默认收起
    
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text(
                text = "更新日志",
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.primary
            )
        },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(400.dp)
                    .verticalScroll(rememberScrollState()),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // 版本 1.0.7
                VersionCard(
                    version = "1.0.7",
                    date = "2025年9月8日",
                    updates = listOf(
                        "• 采集编队查询新增\"实验室查询\"功能，优化查询配置及逻辑，可支持自选参与查询厨师",
                        "• 综合查询新增\"厨师分类查询\"功能"
                    ),
                    isExpanded = version107Expanded,
                    onToggleExpanded = { version107Expanded = !version107Expanded }
                )
                
                // 版本 1.0.6
                VersionCard(
                    version = "1.0.6",
                    date = "2025年8月28日",
                    updates = listOf(
                        "• 新增\"贵客率计算器\"功能，感谢黑龙大佬提供的算法！",
                        "• 优化采集编队的搜索逻辑"
                    ),
                    isExpanded = version106Expanded,
                    onToggleExpanded = { version106Expanded = !version106Expanded }
                )
                
                // 版本 1.0.5.1
                VersionCard(
                    version = "1.0.5.1",
                    date = "2025年8月20日",
                    updates = listOf(
                        "• 新增\"查询桌子收益\"功能",
                        "• 优化查询厨师修炼搜索界面"
                    ),
                    isExpanded = version105Expanded,
                    onToggleExpanded = { version105Expanded = !version105Expanded }
                )
                
                // 版本 1.0.4
                VersionCard(
                    version = "1.0.4",
                    date = "2025年8月18日",
                    updates = listOf(
                        "• 新增一键查询玉片采集配置、保存方案功能",
                        "• 新增用户切换功能，支持保存多用户数据"
                    ),
                    isExpanded = version104Expanded,
                    onToggleExpanded = { version104Expanded = !version104Expanded }
                )
                
                // 版本 1.0.3
                VersionCard(
                    version = "1.0.3",
                    date = "2025年8月14日",
                    updates = listOf(
                        "• 新增\"查询采集编队\"功能，一键查询采集配置",
                        "• 修复部分技法值计算bug"
                    ),
                    isExpanded = version103Expanded,
                    onToggleExpanded = { version103Expanded = !version103Expanded }
                )
                
                // 版本 1.0.2
                VersionCard(
                    version = "1.0.2",
                    date = "2025年8月7日",
                    updates = listOf("• 新增\"查询贵客冲突\"功能"),
                    isExpanded = version102Expanded,
                    onToggleExpanded = { version102Expanded = !version102Expanded }
                )
                
                // 版本 1.0.1
                VersionCard(
                    version = "1.0.1",
                    date = "2025年8月5日",
                    updates = listOf(
                        "• 新增\"个人数据导入\"功能",
                        "• 新增\"查询碰瓷\"功能",
                        "• 新增\"查询厨师修炼\"功能"
                    ),
                    isExpanded = version101Expanded,
                    onToggleExpanded = { version101Expanded = !version101Expanded }
                )
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("关闭")
            }
        }
    )
}

@Composable
private fun VersionCard(
    version: String,
    date: String,
    updates: List<String>,
    isExpanded: Boolean,
    onToggleExpanded: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceVariant
        )
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            // 标题行 - 包含版本号和展开/收起按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Text(
                        text = "版本$version",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Text(
                        text = date,
                        fontSize = 14.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                
                IconButton(
                    onClick = onToggleExpanded,
                    modifier = Modifier.size(32.dp)
                ) {
                    Icon(
                        imageVector = if (isExpanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                        contentDescription = if (isExpanded) "收起" else "展开",
                        tint = MaterialTheme.colorScheme.primary
                    )
                }
            }
            
            // 更新内容 - 根据展开状态显示
            if (isExpanded) {
                Text(
                    text = "更新内容：",
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Medium
                )
                Column(
                    modifier = Modifier.padding(start = 8.dp),
                    verticalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    updates.forEach { update ->
                        Text(
                            text = update,
                            fontSize = 14.sp
                        )
                    }
                }
            }
        }
    }
}